package com.cqie.hospitalescort.handler;

import com.cqie.hospitalescort.DTO.ChatInfoDTO;
import com.cqie.hospitalescort.entity.OnlineChatInfo;
import com.cqie.hospitalescort.exception.BusinessException;
import com.cqie.hospitalescort.service.OnlineChatInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * webSocket三次握手
 */
public class ChatHandler extends TextWebSocketHandler {

    @Autowired
    private OnlineChatInfoService chatService;

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        OnlineChatInfo chatInfo = objectMapper.readValue(message.getPayload(), OnlineChatInfo.class);

        // 保存消息到数据库
        chatService.saveMessage(chatInfo);

        // 广播消息给所有会话
        for (WebSocketSession sess : sessions.values()) {
            sess.sendMessage(new TextMessage(objectMapper.writeValueAsString(chatInfo)));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.put(session.getId(), session);

        if (Objects.isNull(session.getUri())) {
            throw new BusinessException("session的url为空");
        }

        // 获取历史消息并发送给新连接的客户端
        String chatCode = session.getUri().getQuery().split("=")[1];
        List<ChatInfoDTO> messages = chatService.getMessagesByChatCode(chatCode);
        ObjectMapper objectMapper = new ObjectMapper();
        for (ChatInfoDTO msg : messages) {
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(msg)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session.getId());
    }
}